import { useEditor } from '@craftjs/core';
import { Dropdown, type MenuProps } from 'antd';
import React, { useEffect, useMemo } from 'react';
import { DragItem } from '../DragItem';

type NodeBoxProps = {
  id: string;
  children?: React.ReactNode;
};

export const NodeBox: React.FC<NodeBoxProps> = ({ id, children }) => {
  const {
    selected,
    preview,
    hovered,
    actions: { delete: deleteNode, selectNode },
  } = useEditor((state) => {
    const [selected] = Array.from(state.events.selected);
    const [hovered] = Array.from(state.events.hovered);

    return {
      selected: selected === id,
      preview: state.options.enabled,
      hovered: hovered === id,
    };
  });

  const items: MenuProps['items'] = [
    {
      label: 'Delete',
      key: 'DELETE',
      onClick() {
        deleteNode(id);
      },
    },
  ];

  const outline = useMemo(() => {
    if (selected) {
      return '#4096ff';
    }

    return hovered ? '#ff4d4f' : 'transparent';
  }, [selected, hovered]);

  useEffect(() => {
    selectNode(id);
  }, []);

  return preview ? (
    <Dropdown menu={{ items }} trigger={['contextMenu']}>
      <div
        style={{
          padding: 10,
          border: `1px solid ${outline}`,
        }}
      >
        <DragItem>{children}</DragItem>
      </div>
    </Dropdown>
  ) : (
    <DragItem>{children}</DragItem>
  );
};
